﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Management;
using System.Windows.Forms;
//using HalconDotNet;
using System.Drawing;
using System.Drawing.Imaging;
//using System.Data.SQLite;
using System.Data;
using YJYpublicClass.DataStruct;

namespace YJYpublicClass
{
    class PublicFuntions
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath);
        /// <summary>
        /// 强制结束进程
        /// </summary>
        public static void KillProcess(string ProcessName)
        {
            Process[] cur = Process.GetProcesses();
            for (int i = 0; i < cur.Length; i++)
            {
                if (cur[i].ProcessName == ProcessName)
                {
                    cur[i].Kill();
                }
            }
        }


        /// <summary>
        /// 写入数据至INI文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="Value"></param>
        /// <param name="Path"></param>
        public static void WriteINI(string section, string key, string Value, string Path)
        {
            WritePrivateProfileString(section, key, Value, Path);
        }

        /// <summary>
        /// 从INI文件读取数据
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="Standard"></param>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static string GetINI(string section, string key, string Standard, string Path)
        {
            StringBuilder temp = new StringBuilder(255);
            GetPrivateProfileString(section, key, Standard, temp, 255, Path);
            return temp.ToString();
        }

        /// <summary>
        /// 查询文件路径是否存在，不存在则根据路径创建文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="IsCreateFile"></param>
        public static void CreateFile(string FilePath)
        {
            try
            {
                if (System.IO.File.Exists(FilePath) == false)
                {
                    System.IO.Directory.CreateDirectory(FilePath);
                }
            }
            catch (Exception ex)
            {
             
            }
        }
        ///查找语言转换表
        ///



        /// <summary>
        /// 打开任意类型文档
        /// </summary>
        /// <param name="Path"></param>
        public static void OpenDocument(string Path)
        {
            try
            {
                if (System.IO.File.Exists(Path))
                {
                    System.Diagnostics.Process.Start(Path);
                }
                else
                {
                    MessageBox.Show("未找到帮助文档,请在【系统配置】界面设置帮助文档路径！");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 获取当前软件的内存占用
        /// </summary>
        public static string GetSoftWareARM()
        {
            try
            {
                Process CurrentProcess = Process.GetCurrentProcess();
                return (CurrentProcess.WorkingSet64 / 1024 / 1024).ToString();
            }
            catch (Exception)
            {
                return "运存获取失败!";
            }
        }

        public static long GetHardDiskSpace(string str_HardDiskName)
        {

            long totalSize = new long();

            str_HardDiskName = str_HardDiskName + ":\\";

            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();

            foreach (System.IO.DriveInfo drive in drives)
            {

                if (drive.Name == str_HardDiskName)
                {

                    totalSize = drive.TotalSize / (1024 * 1024 * 1024);

                }

            }

            return totalSize;

        }

        /// <summary>  

        /// 获取指定驱动器的剩余空间总大小(单位为GB)  

        /// </summary>  

        /// <param name=”str_HardDiskName”>只需输入代表驱动器的字母即可 </param>  

        /// <returns> </returns>  

        public static long GetHardDiskFreeSpace(string str_HardDiskName)
        {

            long freeSpace = new long();

            str_HardDiskName = str_HardDiskName + ":\\";

            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();

            foreach (System.IO.DriveInfo drive in drives)
            {

                if (drive.Name == str_HardDiskName)
                {

                    freeSpace = drive.TotalFreeSpace / (1024 * 1024 * 1024);

                }

            }

            return freeSpace;

        }


        /// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="ho_Image"></param>
        /// <param name="hv_Window"></param>
        //public static void DispImage(HObject ho_Image, HWindow hv_Window)
        //{
        //    HTuple hv_Width, hv_Height;
        //    try
        //    {
        //        HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);
        //        HOperatorSet.SetPart(hv_Window, 0, 0, hv_Height - 1, hv_Width - 1);
        //        HOperatorSet.DispObj(ho_Image, hv_Window);
        //    }
        //    catch (Exception)
        //    {
        //    }
        //}

        //public static void DispImagekeepbilv(HObject ho_Image, HWindow hv_Window)
        //{
        //    HTuple hv_Width, hv_Height;
        //    try
        //    {
        //        HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);
        //        HOperatorSet.GetWindowExtents(hv_Window, out HTuple row, out HTuple col, out HTuple wwdith, out HTuple wwheight);


        //        double picWHRatio = 1.0 * hv_Width / hv_Height;
        //        double winWHRatio = 1.0 * wwdith / wwheight;
        //        if (picWHRatio >= winWHRatio)
        //        {
        //            int dispWidth = hv_Width;
        //            int dispHeight = (int)(hv_Width.I / winWHRatio);
        //            int offset = (dispHeight - hv_Height) / 2;
        //            // dev_set_part(-offset, 0, dispHeight - offset, dispWidth);
        //            HOperatorSet.SetPart(hv_Window, -offset, 0, dispHeight - offset, dispWidth);
        //        }
        //        else
        //        {
        //            int dispWidth = (int)(hv_Height.I * winWHRatio);
        //            int dispHeight = hv_Height;
        //            int offset = (dispWidth - hv_Width) / 2;
        //            // dev_set_part(-offset, 0, dispHeight - offset, dispWidth);
        //            HOperatorSet.SetPart(hv_Window, 0, -offset, dispHeight, dispWidth - offset);
        //        }
        //        HOperatorSet.DispObj(ho_Image, hv_Window);
        //    }
        //    catch (Exception)
        //    {
        //    }
        //}
        ////OKNG
        //public static ResultFunc SaveImagebyPath(HObject hImage, string path, bool isOK)
        //{
            
        //    string SubImageFolder = null;
        //    try
        //    {
        //        if (isOK) { SubImageFolder = path + "\\OKImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        else { SubImageFolder = path + "\\NGImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        PublicFuntions.CreateFile(SubImageFolder);
        //        string NowTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
        //        string SaveImageName = SubImageFolder + "\\" + NowTime + ".jpg";                        //原图保存为jpg格式
        //        HOperatorSet.WriteImage(hImage, "jpg", 0, SaveImageName);
        //        return new ResultFunc();
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ResultFunc(Funstate.异常, ex.Message);
        //    }
        //}
       
        //public static ResultFunc SaveImagebyPath(HObject hImage, string path, bool isOK, string houzui)
        //{

        //    string SubImageFolder = null;
        //    try
        //    {
        //        if (isOK) { SubImageFolder = path + "\\OKImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        else { SubImageFolder = path + "\\NGImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        PublicFuntions.CreateFile(SubImageFolder);
        //        string NowTime = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
        //        string SaveImageName = SubImageFolder + "\\" + NowTime +"_" +houzui + ".jpg";                        //原图保存为jpg格式
        //        HOperatorSet.WriteImage(hImage, "jpg", 0, SaveImageName);
        //        return new ResultFunc();
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ResultFunc(Funstate.异常, ex.Message);
        //    }
        //}

        //public static ResultFunc SaveWImagebyPath(HTuple windowID, string path, bool isOK, string houzui)
        //{
        //    string SubImageFolder = null;
        //    HObject windowImage = null;
        //    HOperatorSet.GenEmptyObj(out windowImage);
        //    try
        //    {
        //        if (isOK) { SubImageFolder = path + "\\OKImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        else { SubImageFolder = path + "\\NGImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        PublicFuntions.CreateFile(SubImageFolder);
        //        string NowTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
        //        HOperatorSet.DumpWindowImage(out windowImage, windowID);
        //        string ProcessImageName = SubImageFolder + "\\" + NowTime + "_" + houzui + "_0.jpg";                     //效果图保存为jpg格式,png压缩费时间
        //        HOperatorSet.WriteImage(windowImage, "jpg", 0, ProcessImageName);
        //        windowImage.Dispose();

        //        return new ResultFunc();
        //    }
        //    catch (Exception ex)
        //    {
        //        windowImage.Dispose();
        //        return new ResultFunc(Funstate.异常, ex.Message);
        //    }
        //}

        //public static ResultFunc SaveImagebyPath(Mat hImage, string path, bool isOK, string houzui)
        //{

        //    string SubImageFolder = null;
        //    try
        //    {
        //        if (isOK) { SubImageFolder = path + "\\OKImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        else { SubImageFolder = path + "\\NGImage\\" + System.DateTime.Now.ToString("yyyyMMdd"); }
        //        PublicFuntions.CreateFile(SubImageFolder);
        //        string NowTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
        //        string SaveImageName = SubImageFolder + "\\" + NowTime + "_" + houzui + ".jpg";                        //原图保存为jpg格式
        //        hImage.Save(SaveImageName);
        //      //  HOperatorSet.WriteImage(hImage, "jpg", 0, SaveImageName);
        //        return new ResultFunc();
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ResultFunc(Funstate.异常, ex.Message);
        //    }
        //}

        ////仅仅时保存
        //public static ResultFunc SaveImagebyPath(HObject hImage, string path)
        //{
        //    string SubImageFolder = null;
        //    try
        //    {
        //        SubImageFolder = path + System.DateTime.Now.ToString("yyyyMMdd");
        //        PublicFuntions.CreateFile(SubImageFolder);
        //        string NowTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
        //        string SaveImageName = SubImageFolder + "\\" + NowTime + ".jpg";                        //原图保存为jpg格式
        //        HOperatorSet.WriteImage(hImage, "jpg", 0, SaveImageName);
        //        return new ResultFunc();
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ResultFunc(Funstate.异常, ex.Message);
        //    }
        //}



        /// <summary>
        /// 保存日志运行记录
        /// </summary>
        public static void SaveLog(string Path, string LogMessage)
        {
            try
            {
                string LogPath = Path + "//" + System.DateTime.Now.ToString("yyyyMMdd") + ".txt";
                CreateFile(Path);
                System.IO.File.AppendAllText(LogPath, "\r\n" + LogMessage);
            }
            catch (Exception ex)
            {
               
            }
        }

        /// <summary>
        /// 保存异常日志
        /// </summary>
        /// <param name="path：路径"></param>
        /// <param name="ErrorMessage：错误信息"></param>
        public static void SaveErrorLog(string path, string ErrorMessage)
        {
            try
            {
                string LogPath = path + "//" + System.DateTime.Now.ToString("yyyyMMdd") + "ErrorLog.txt";
                CreateFile(path);
                string SaveErrorData = DateTime.Now.ToString("HH:mm:ss") + ">>>" + ErrorMessage;
                System.IO.File.AppendAllText(LogPath, "\r\n" + SaveErrorData);
            }
            catch (Exception)
            {

            }

        }

        /// <summary>
        /// 固定间隔删除文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Interval"></param>
        public static ResultFunc DeleateFile(string FilePath, int Interval)
        {
            ResultFunc ResultFunc = new ResultFunc();
            try
            {
                DirectoryInfo rootDirInfo = new DirectoryInfo(FilePath);
                if (!rootDirInfo.Exists) {
                    ResultFunc.mes = "文件目录不存在";
                    return ResultFunc; }
                DateTime NowTime = DateTime.Now;
                FileSystemInfo[] dirs = rootDirInfo.GetFileSystemInfos();

                foreach (var item in dirs)
                {
                    DateTime CreateFileTime = item.CreationTime;
                    TimeSpan OutTime = NowTime - CreateFileTime;
                    if (OutTime.Days > Interval)
                    {
                        FileAttributes Attr = File.GetAttributes(item.FullName);
                        if (Attr == FileAttributes.Directory) { Directory.Delete(item.FullName, true); }
                        else { item.Delete(); }
                    }
                }
                return ResultFunc;
            }
            catch (Exception ex)
            {
                ResultFunc.State = Funstate.异常;
                ResultFunc.mes = "文件目录不存在";
                return ResultFunc;
            }
        }
 

        //加密

        public static int ValuesUpDownlimit(ref int value, int downlimit, int uplimit)
        {
            if (value > uplimit)
            {
                value = uplimit;
            }
            else if (value < downlimit)
            {
                value = downlimit;
            }
            return value;
        }
        public static double ValuesUpDownlimit(ref double value, double downlimit, double uplimit)
        {
            if (value > uplimit)
            {
                value = uplimit;
            }
            else if (value < downlimit)
            {
                value = downlimit;
            }
            return value;
        }

        /// <summary>
        /// halcon 图像对象转bitmap，适用于halcon12以下版本，转换需要几十ms。
        /// </summary>
        /// <param name="h_Image"></param>
        /// <param name="res24"></param>
        //public static void HObject2Bpp24_L(HObject image, out Bitmap res24)
        //{
        //    try
        //    {
        //        HTuple hred, hgreen, hblue, type, width, height;

        //        HOperatorSet.GetImagePointer3(image, out hred, out hgreen, out hblue, out type, out width, out height);
        //        byte[] red = new byte[width * height];
        //        byte[] green = new byte[width * height];
        //        byte[] blue = new byte[width * height];
        //        Marshal.Copy(hred, red, 0, width * height);
        //        Marshal.Copy(hgreen, green, 0, width * height);
        //        Marshal.Copy(hblue, blue, 0, width * height);
        //        Bitmap res32 = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

        //        Rectangle rect = new Rectangle(0, 0, width, height);
        //        BitmapData bitmapData = res32.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
        //        unsafe
        //        {
        //            byte* bptr = (byte*)bitmapData.Scan0;

        //            int lengh = width * height;
        //            for (int i = 0; i < lengh; i++)
        //            {
        //                bptr[i * 4] = blue[i];
        //                bptr[i * 4 + 1] = green[i];
        //                bptr[i * 4 + 2] = red[i];
        //                bptr[i * 4 + 3] = 255;
        //            }
        //        }
        //        res32.UnlockBits(bitmapData);

        //        //32位Bitmap转24位
        //        res24 = new Bitmap(res32.Width, res32.Height, PixelFormat.Format24bppRgb);
        //        Graphics graphics = Graphics.FromImage(res24);
        //        graphics.DrawImage(res32, new Rectangle(0, 0, res32.Width, res32.Height));

        //        res32.Dispose();
        //    }
        //    catch (Exception ex)
        //    {

        //        res24 = null;
        //    }
        //}
        ///// <summary>
        ///// halcon 图像对象转bitmap，适用于halcon18以上的版本，效率比老版本高一些，但是依然费。
        ///// </summary>
        ///// <param name="h_Image"></param>
        ///// <param name="res24"></param>
        //public static void HObject2Bpp24_H(HObject h_Image, out Bitmap res24)
        //{
        //    try
        //    {
        //        HTuple width0, height0, type, width, height;
        //        //获取图像尺寸
        //        HOperatorSet.GetImageSize(h_Image, out width0, out height0);
        //        //创建交错格式图像
        //        HOperatorSet.InterleaveChannels(h_Image, out HObject InterImage, "argb", "match", 255);

        //        //获取交错格式图像指针
        //        HOperatorSet.GetImagePointer1(InterImage, out HTuple Pointer, out type, out width, out height);
        //        IntPtr ptr = Pointer;
        //        //构建新Bitmap图像
        //        Bitmap res32 = new Bitmap(width / 4, height, width, PixelFormat.Format32bppArgb, ptr);

        //        //32位Bitmap转24位
        //        res24 = new Bitmap(res32.Width, res32.Height, PixelFormat.Format24bppRgb);
        //        Graphics graphics = Graphics.FromImage(res24);
        //        graphics.DrawImage(res32, new Rectangle(0, 0, res32.Width, res32.Height));

        //        res32.Dispose();

        //    }
        //    catch (Exception ex)
        //    {
        //        res24 = null;

        //    }
        //}

        //public static Boolean HObject2CV(HObject h_image, out Mat cv_imagemat)
        //{
        //    cv_imagemat = new Mat();
        //    try
        //    {
        //        HOperatorSet.GetImagePointer3(h_image, out HTuple R, out HTuple G, out HTuple B, out HTuple type, out HTuple width2, out HTuple height2);

        //        Mat[] images = new Mat[3];

        //        //根据指针拷贝数据
        //        Image<Gray, byte> Rc = new Image<Gray, byte>(width2, height2, width2, R);
        //        Image<Gray, byte> Gc = new Image<Gray, byte>(width2, height2, width2, G);
        //        Image<Gray, byte> Bc = new Image<Gray, byte>(width2, height2, width2, B);
        //        images[0] = Bc.Mat;
        //        images[1] = Gc.Mat;
        //        images[2] = Rc.Mat;
        //        VectorOfMat imagesmat = new VectorOfMat(images);
        //        Mat outImage = new Mat();
        //        outImage.Create(height2, width2, DepthType.Cv8U, 3);

        //        CvInvoke.Merge(imagesmat, cv_imagemat);
        //        return true;
        //    }
        //    catch (Exception)
        //    {
        //        return false;
        //    }

        //}



        public static object locobej = new object();
        //public static string LangeuageChange(string chinese, int Lanchoice)
        //{
        //    //如果没有查到等于本身
        //    string strreturn = chinese;
        //    if (Lanchoice == 1)
        //    {
        //        return strreturn;
        //    }
        //    else
        //    {
        //        lock (locobej)
        //        {
        //            string connectionString = "data source=中英文对应.db";
        //            SQLiteConnection con = new SQLiteConnection(connectionString);
        //            try
        //            {

        //                con.Open();
        //                SQLiteCommand cmd = new SQLiteCommand(con);

        //                // SQLiteCommand command = new SQLiteCommand("SELECT * FROM Customers", connection);
        //                cmd.CommandText = string.Format("select * from 中英对照表 where 中文 = '{0}'", chinese);
        //                SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
        //                DataTable table = new DataTable();
        //                adapter.Fill(table);
        //                //直接去找
        //                if (table.Rows.Count > 0)
        //                {
        //                    try
        //                    {
        //                        switch (Lanchoice)
        //                        {
        //                            case 1:
        //                                strreturn = (string)table.Rows[0]["中文"];
        //                                break;
        //                            case 2:
        //                                strreturn = (string)table.Rows[0]["英文"];
        //                                break;
        //                            case 3:
        //                                strreturn = (string)table.Rows[0]["泰文"];
        //                                break;
        //                            case 4:
        //                                strreturn = (string)table.Rows[0]["越南文"];
        //                                break;
        //                            default:
        //                                break;

        //                        }

        //                    }
        //                    catch
        //                    {
        //                        strreturn = chinese;
        //                    }
        //                }
        //                else
        //                {
        //                    //插入
        //                    cmd.CommandText = string.Format("insert into  中英对照表 (中文) values('{0}');", chinese);
        //                    cmd.ExecuteNonQuery();
        //                }
        //                if (!string.IsNullOrWhiteSpace(strreturn))
        //                {
        //                    return strreturn;
        //                }
        //                else
        //                {
        //                    return chinese;
        //                }

        //            }
        //            catch (Exception ex)
        //            {
        //                //  MessageBox.Show(ex.Message);
        //                return "转换错误";
        //            }
        //            finally
        //            {
        //                con.Close();
        //            }
        //        }
        //    }

        //}


        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

    }
}


